<template>
  <div class="shelf-manage-page">
    <el-card style="max-width: 1200px; margin: 0 auto;">
      <div class="toolbar">
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="onAdd">新增货架</el-button>
      </div>
      <el-form v-if="formVisible" :model="form" label-width="90px" style="max-width: 400px; margin-bottom: 24px;">
        <el-form-item label="所属分区" required>
          <el-select v-model="form.zoneId" style="width: 180px">
            <el-option v-for="z in zoneList" :key="z.id" :label="getZoneLabel(z)" :value="z.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="货架名称" required>
          <el-input v-model="form.name" maxlength="10" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.desc" maxlength="30" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSave">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="shelfList" border size="small" style="margin-bottom: 0;">
        <el-table-column label="货架名称">
          <template #default="scope">
            <span>{{ getWarehouseName(getZoneWarehouseId(scope.row.zoneId)) }} - {{ getZoneName(scope.row.zoneId) }} - {{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <div style="display: flex; gap: 8px; justify-content: flex-start; padding-left: 8px;">
              <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
// 假设locationList为全局/父组件/Pinia数据，这里用mock
const locationList = ref([
  { id: 1, shelf: 1, zone: 1, stock: 60 },
  { id: 2, shelf: 1, zone: 1, stock: 80 },
  { id: 3, shelf: 3, zone: 2, stock: 30 }
])
function canDeleteShelf(shelfId: number, zoneId?: number) {
  return !locationList.value.some(l => l.shelf === shelfId && l.zone === zoneId && l.stock > 0)
}
const router = useRouter()
const warehouseList = ref([
  { id: 1, name: '上海仓' },
  { id: 2, name: '北京仓' }
])
const zoneList = ref([
  { id: 1, warehouseId: 1, name: 'A区' },
  { id: 2, warehouseId: 1, name: 'B区' },
  { id: 3, warehouseId: 2, name: 'C区' }
])
const shelfList = ref([
  { id: 1, zoneId: 1, name: 'A1货架', desc: 'A区主货架', sort: 1 },
  { id: 2, zoneId: 1, name: 'A2货架', desc: 'A区副货架', sort: 2 },
  { id: 3, zoneId: 2, name: 'B1货架', desc: 'B区主货架', sort: 1 },
  { id: 4, zoneId: 3, name: 'C1货架', desc: 'C区主货架', sort: 1 }
])
const formVisible = ref(false)
const isEdit = ref(false)
const form = ref({ id: 0, zoneId: 0, name: '', desc: '', sort: 1 })
function getWarehouseName(id: number) {
  return warehouseList.value.find(w => w.id === id)?.name || ''
}
function getZoneName(id: number) {
  return zoneList.value.find(z => z.id === id)?.name || ''
}
function getZoneWarehouseId(zoneId: number) {
  const zone = zoneList.value.find(z => z.id === zoneId)
  return zone?.warehouseId || 0
}
function getZoneLabel(z: any) {
  return getWarehouseName(z.warehouseId) + ' - ' + z.name
}
function onAdd() {
  form.value = { id: 0, zoneId: zoneList.value[0]?.id || 0, name: '', desc: '', sort: 1 }
  isEdit.value = false
  formVisible.value = true
}
function onEdit(row: any) {
  form.value = { ...row }
  isEdit.value = true
  formVisible.value = true
}
function onSave() {
  if (!form.value.name) return ElMessage.warning('请输入货架名称')
  if (!form.value.zoneId) return ElMessage.warning('请选择所属分区')
  // 找到当前分区的所属仓库id
  const currentZone = zoneList.value.find(z => z.id === form.value.zoneId)
  const warehouseId = currentZone?.warehouseId
  // 校验同一仓库+分区下货架名称不能重复
  const isDuplicate = shelfList.value.some(s => {
    if (s.id === form.value.id && isEdit.value) return false
    const sZone = zoneList.value.find(z => z.id === s.zoneId)
    return s.name === form.value.name && s.zoneId === form.value.zoneId && sZone?.warehouseId === warehouseId
  })
  if (isDuplicate) return ElMessage.error('同一仓库下同一分区的货架名称已存在，不允许重名！')
  if (isEdit.value) {
    const idx = shelfList.value.findIndex(t => t.id === form.value.id)
    if (idx > -1) shelfList.value[idx] = { ...form.value }
    ElMessage.success('货架修改成功')
  } else {
    shelfList.value.push({
      id: Date.now(),
      zoneId: form.value.zoneId,
      name: form.value.name,
      desc: form.value.desc,
      sort: form.value.sort
    })
    ElMessage.success('货架新增成功')
  }
  formVisible.value = false
}
function onCancel() {
  formVisible.value = false
}
function onDelete(row: any) {
  if (!canDeleteShelf(row.id, row.zoneId)) {
    ElMessage.error('该货架下存在商品库存，无法删除！')
    return
  }
  ElMessageBox.confirm('确定要删除该货架吗？', '提示', { type: 'warning' })
    .then(() => {
      shelfList.value = shelfList.value.filter(t => t.id !== row.id)
      ElMessage.success('删除成功')
    })
}
</script>

<style scoped>
.shelf-manage-page { padding: 24px; background: #f7f8fa; min-height: 100vh; }
.toolbar { display: flex; gap: 12px; margin-bottom: 24px; align-items: center; }
</style> 